<script setup lang="ts">
import { getEntityNameListApi } from "@/common/apis/scn"
import SelectEvent from "@/common/components/SelectEvent/index.vue"
import type { EditInfrenceBasicInfo, DataCollection, Opportunity } from "@/common/apis/train/type"
import { FormTypeEnum } from "@/common/constants/other-keys"
import { ref, computed, nextTick, watch, Ref } from "vue"

interface Props {
  dialogType: FormTypeEnum
  ruleForm: EditInfrenceBasicInfo
  isEdit?: boolean
}
const props = defineProps<Props>()
const emit = defineEmits(["update:ruleForm"])

const allOptions = ['态势', '动作', '装备性能', '任务数据']

// 定义接口来规范类型
interface EntityItem {
  name: string;
  data: string[];
  freq: string;
}

// 添加is_enable属性用于本地UI状态
interface LocalDataCollection extends Omit<DataCollection, 'opportunity'> {
  is_enable: boolean;
  opportunity: Omit<Opportunity, 'value'> & { value: any }; // 使用any临时绕过类型检查
  entity_list: EntityItem[];
  event: string[];
}

const data_collections = ref<LocalDataCollection>({
  is_enable: false,
  opportunity: {
    value: 0, // Node[]类型，但在UI中我们使用数字，在提交时转换
    key_events: [] as string[],
    time_range: {
      start_time: '',
      end_time: '',
    }
  },
  entity_list: [] as EntityItem[],
  event: [] as string[]
})

const handleEvent = () => {
}

// 表格引用，用于手动控制表格选择状态
const tableRef = ref<any>(null)

// 记录选中行的映射表
const selectedRowMap = ref(new Map<string, boolean>())

const isInitializing = ref(false)

// 处理采集数据复选框变化
const handleData = (values: string[], row: EntityItem) => {
  if (isInitializing.value) return
  // 如果有选中的选项，则选中该行
  if (values.length > 0) {
    // 记录这一行被选中
    selectedRowMap.value.set(row.name, true)
    // 手动选中表格行（不触发回调）
    if (tableRef.value) {
      tableRef.value.toggleRowSelection(row, true)
    }
  } else {
    // 如果没有选中的选项，取消选中该行
    selectedRowMap.value.delete(row.name)
    // 手动取消选中表格行（不触发回调）
    if (tableRef.value) {
      tableRef.value.toggleRowSelection(row, false)
    }
  }

  // 确保 entity_list 始终保持最新
  updateEntityList()
}

// 更新 entity_list
const updateEntityList = () => {
  // 获取所有当前选中的行
  const selectedRows = data_collectionsEntity_list.value.filter(row =>
    selectedRowMap.value.has(row.name) || row.data.length > 0
  )
  data_collections.value.entity_list = selectedRows
}

const data_collectionsEntity_list = ref<EntityItem[]>([])
const detailForm = ref()
const scnId = ref()
watch(
  () => props.ruleForm.sim_config.scn_id,
  (newRuleForm) => {
    scnId.value = newRuleForm
    if (!scnId.value) return
    // 新增推演，需要选择想定，才能触发调用实体数据接口
    getEntityNameListApi(scnId.value).then((res: any) => {
      data_collectionsEntity_list.value = res.data.map((name: any) => ({
        name,
        data: [],
        freq: ''
      }))
      // isInitializing.value = false
    })
  },
  { immediate: true, deep: true }
)
watch(
  () => props.ruleForm.data_collections,
  (newForm) => {
    isInitializing.value = true
    detailForm.value = newForm
    data_collections.value.is_enable = newForm.is_enable
    if (!scnId.value) {
      isInitializing.value = false
      return
    }
    getEntityNameListApi(scnId.value).then((res: any) => {
      // 1. 先生成表格数据
      data_collectionsEntity_list.value = res.data.map((name: any) => ({
        name,
        data: [],
        freq: ''
      }))
      // 2. 合并详情选中状态
      data_collectionsEntity_list.value.forEach(item => {
        newForm.entity_list.forEach(e => {
          if (e.name === item.name) {
            // 深拷贝，避免引用污染
            item.data = Array.isArray(e.data) ? [...e.data] : []
            item.freq = e.freq
          }
        })
      })
      // 3. nextTick + setTimeout 双重保险，确保 el-table 渲染完成后同步选中
      nextTick(() => {
        setTimeout(() => {
          if (tableRef.value) {
            tableRef.value.clearSelection()
            data_collectionsEntity_list.value.forEach(row => {
              // 只用 entity_list 判断
              if (newForm.entity_list.find(e => e.name === row.name)) {
                tableRef.value.toggleRowSelection(row, true)
              }
            })
          }
          setTimeout(() => {
            isInitializing.value = false
          }, 200)
        }, 0)
      })
    })
    data_collections.value.event = newForm.event
  },
  { immediate: true, deep: true }
)
watch(
  () => props.isEdit,
  (newisEdit) => {
    if (newisEdit) {
      data_collections.value.is_enable = newisEdit
    }
  },
  { immediate: true, deep: true }
)

// 你的原始存储（秒数）
const startTimeStr = ref('00:00:00');  // 默认开始时间
const endTimeStr = ref('03:00:00');    // 默认结束时间

watch(
  () => [detailForm.value.opportunity.time_range?.start_time, detailForm.value.opportunity.time_range?.end_time],
  ([startTime, endTime]) => {
    if (!startTime || !endTime) return;
    if (props.dialogType === FormTypeEnum.CREATE) {
      // 创建页面时，保持默认值
      startTimeStr.value = '00:00:00';
      endTimeStr.value = '03:00:00';
    } else {
      startTimeStr.value = startTime;
      endTimeStr.value = endTime;
    }
  },
);

// 选择后存数据
watch([startTimeStr, endTimeStr], ([start, end]) => {
  // 如果时间选择框没有选择，使用默认值
  data_collections.value.opportunity.time_range.start_time = start
  data_collections.value.opportunity.time_range.end_time = end
  const sratrHour = parseInt(start.split(":")[0], 10)
  const endHour = parseInt(end.split(":")[0], 10)
  // 如果选择的是3点，则禁用分钟和秒，并且将分钟秒设置为00
  if (sratrHour === 3) {
    startTimeStr.value = "03:00:00" // 自动将分钟和秒设置为 00
  }
  if (endHour === 3) {
    endTimeStr.value = "03:00:00" // 自动将分钟和秒设置为 00
  }
}, { immediate: true });

// 分别生成两组 disabled 函数
function makeDisabled(timeStrRef: Ref<string>) {
  const full60 = Array.from({ length: 60 }, (_, i) => i)
  return {
    // 只允许 0-3 点
    hours: () => Array.from({ length: 24 }, (_, i) => i).filter(i => i > 3),
    // 如果小时是 3，就禁掉所有分钟
    minutes: () => {
      const h = parseInt(timeStrRef.value.split(':')[0], 10)
      return h === 3 ? full60 : []
    },
    // 如果小时是 3，就禁掉所有秒
    seconds: () => {
      const h = parseInt(timeStrRef.value.split(':')[0], 10)
      return h === 3 ? full60 : []
    }
  }
}
// 绑定el-time-picker实现禁用
const startDisabled = makeDisabled(startTimeStr)
const endDisabled   = makeDisabled(endTimeStr)

const localRuleForm = computed({
  get: () => props.ruleForm,
  set: (newValue) => {
    emit("update:ruleForm", newValue)
  }
})
function getRowKeys(row: EntityItem) {
  return row.name
}

// 表格选择改变事件
function handleSelectionChange(selectedRows: EntityItem[]) {
  if (isInitializing.value) return
  // 遍历所有行
  data_collectionsEntity_list.value.forEach(row => {
    // 检查当前行是否在选中行列表中
    const isSelected = selectedRows.some(selectedRow => selectedRow.name === row.name)

    // 更新映射表
    if (isSelected) {
      selectedRowMap.value.set(row.name, true)
      // 如果选中了行，且采集数据为空，则全选采集数据
      if (row.data.length === 0) {
        row.data = [...allOptions]
      }
      // 如果选中行且采集频率为空，则默认设置为"1"
      if (row.freq === '') {
        row.freq = "1"
      }
    } else {
      selectedRowMap.value.delete(row.name)
      // 如果取消选中行，清空采集数据
      row.data = []
      // 如果取消选中行，清空采集频率
      row.freq = ''
    }
  })

  // 更新 entity_list
  data_collections.value.entity_list = selectedRows
}

// 处理采集频率输入
function handleFreqInput(value: string, row: EntityItem) {
  if (isInitializing.value) return
  if (value && value.trim() !== '') {
    // 如果输入了有效值，自动选中该行
    if (tableRef.value && !selectedRowMap.value.has(row.name)) {
      tableRef.value.toggleRowSelection(row, true)
      selectedRowMap.value.set(row.name, true)
      // 如果采集数据为空，则全选采集数据
      if (row.data.length === 0) {
        row.data = [...allOptions]
      }
      // 确保 entity_list 保持最新
      updateEntityList()
    }
  }
}
// 将data_collections.value值赋给localRuleForm.value
const updateData = () => {
  localRuleForm.value.data_collections = data_collections.value
  const v = data_collections.value.opportunity.value
  // 1. 深拷贝，避免直接修改原 ref 对象
  const cleaned = JSON.parse(JSON.stringify(data_collections.value))
  // 2. 根据 value 删除不需要的字段
  if (v === 0) {
    // value = 0：删除 key_events 和 time_range
    delete cleaned.opportunity.key_events
    delete cleaned.opportunity.time_range
  } else if (v === 1) {
    // value = 1：删除 time_range
    delete cleaned.opportunity.time_range
  } else if (v === 2) {
    // value = 2：删除 key_events
    delete cleaned.opportunity.key_events
  }
  // 3. 赋值给 localRuleForm，
  localRuleForm.value.data_collections = cleaned
}

// 暴露验证方法给父组件
defineExpose({
  validate: async () => {
    // 数据采集不需要验证，直接返回true
    return true
  },
  updateData
})

</script>
<template>
  <div class="steps-wrapper">
    <div class="cpi-header-title">
      <SvgIcon name="info-title" />
      <span class="cpi-header-text">数据采集</span>
    </div>
    <div class="engine-config-is">
      <span style="display: inline-block;">是否采集：</span>
      <el-radio-group v-model="data_collections.is_enable" v-if="isEdit || dialogType == FormTypeEnum.CREATE">
        <el-radio :value="true">是</el-radio>
        <el-radio :value="false">否</el-radio>
      </el-radio-group>
      <div v-else>
        <span>{{ detailForm.is_enable ? '是' : '否' }}</span>
      </div>
    </div>

    <div v-if="data_collections.is_enable">
      <div class="engine-config-title">
        <SvgIcon name="info-little-title" /><span>采集时机</span>
      </div>
      <!-- 采集时机选择 -->
      <div class="engine-config-radio" v-if="isEdit || dialogType == FormTypeEnum.CREATE">
        <el-radio-group v-model="data_collections.opportunity.value" class="radio-group-row" size="small">
          <div class="radio-wrapper">
            <el-radio :label="0">开始就采</el-radio>
          </div>
          <div class="radio-wrapper">
            <el-radio :label="1">到达某一关键事件开始采集</el-radio>
            <SelectEvent v-if="data_collections.opportunity.value === 1"
              v-model:task_tags="data_collections.opportunity.key_events" />
          </div>
          <div class="radio-wrapper">
            <el-radio :label="2">特定时间段</el-radio>
            <div v-if="data_collections.opportunity.value === 2">
              <el-time-picker v-model="startTimeStr" format="HH:mm:ss" value-format="HH:mm:ss" :clearable="false"
                placeholder="开始时间" :disabled-hours="startDisabled.hours" :disabled-minutes="startDisabled.minutes"
                :disabled-seconds="startDisabled.seconds" />
              <el-time-picker v-model="endTimeStr" format="HH:mm:ss" value-format="HH:mm:ss" :clearable="false"
                placeholder="结束时间" :disabled-hours="endDisabled.hours" :disabled-minutes="endDisabled.minutes"
                :disabled-seconds="endDisabled.seconds" />
            </div>
          </div>
        </el-radio-group>
      </div>
      <!-- 采集时机详情 -->
      <div v-else class="engine-config-radio-detail">
        <div v-if="detailForm.opportunity?.value === 0">开始就采</div>
        <div v-if="detailForm.opportunity?.value === 1 && detailForm.opportunity.value === 1">
          <div class="event" v-for="item in detailForm.opportunity.key_events" :key="item">{{ item }}</div>
        </div>
        <div v-if="detailForm.opportunity?.value === 2 && detailForm.opportunity.value === 2">
          开始时间：{{ startTimeStr }}&nbsp;&nbsp;&nbsp;&nbsp;结束时间：{{ endTimeStr }}
        </div>
      </div>
      <div class="engine-config-title">
        <SvgIcon name="info-little-title" /><span>实体数据</span>
      </div>
      <div class="engine-config-table">
        <!-- 实体数据选择 -->
        <el-table ref="tableRef" :data="data_collectionsEntity_list" style="width: 100%;height:450px"
          v-show="isEdit || dialogType == FormTypeEnum.CREATE" :row-key="getRowKeys"
          @selection-change="handleSelectionChange">
          <el-table-column type="selection" align="center" :reserve-selection="true" width="55" />
          <el-table-column prop="name" label="实体名称" width="300" />
          <el-table-column label="采集数据" align="center">
            <template #default="{ row }">
              <div style="display: flex; align-items: center; gap: 16px; justify-content: center;">
                <el-checkbox-group v-model="row.data" style="display: flex; align-items: center;"
                  @change="(values: string[]) => handleData(values, row)">
                  <el-checkbox value="态势" size="small">态势</el-checkbox>
                  <el-checkbox value="动作" size="small">动作</el-checkbox>
                  <el-checkbox value="装备性能" size="small">装备性能</el-checkbox>
                  <el-checkbox value="任务数据" size="small">任务数据</el-checkbox>
                </el-checkbox-group>
              </div>
            </template>
          </el-table-column>
          <!-- 采集频率，包含输入框 -->
          <el-table-column label="采集频率" align="center" width="400">
            <template #default="{ row }">
              <el-input v-model="row.freq" placeholder="请输入" size="small"
                @input="(value) => handleFreqInput(value, row)" />
            </template>
          </el-table-column>
        </el-table>
        <!-- 实体数据详情 -->
        <el-table :data="detailForm.entity_list" tyle="width: 100%"
          v-show="!isEdit && dialogType !== FormTypeEnum.CREATE">
          <el-table-column prop="name" label="实体名称" width="300" />
          <el-table-column label="采集数据" align="center"> <template #default="{ row }">
              <div class="event" v-for="item in row.data" :key="item">
                {{ item }}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="freq" label="采集频率" align="center" />
        </el-table>
      </div>
      <div class="engine-config-title">
        <SvgIcon name="info-little-title" />导条指令/事件数据
      </div>
      <div class="engine-config-radio">
        <el-checkbox-group @change="handleEvent" v-model="data_collections.event"
          v-if="isEdit || dialogType == FormTypeEnum.CREATE">
          <el-checkbox value="兵力救援">兵力救援</el-checkbox>
          <el-checkbox value="环境增加">环境增加</el-checkbox>
          <el-checkbox value="障碍物">障碍物</el-checkbox>
          <el-checkbox value="交战/开火">交战/开火</el-checkbox>
          <el-checkbox value="到达目标区域">到达目标区域</el-checkbox>
          <el-checkbox value="爆炸">爆炸</el-checkbox>
          <el-checkbox value="目标丢失">目标丢失</el-checkbox>
        </el-checkbox-group>
        <div v-else style="display: flex;gap:10px">
          <div v-for="item in detailForm.event" :key="item">
            {{ item }}
          </div>
          <div v-if="data_collections.event.length === 0">无</div>
        </div>
      </div>
    </div>

  </div>
</template>
<style lang="scss" scoped>
.steps-wrapper {
  padding: 20px;
  margin-top: 20px;
  width: 100%;
  height: auto;
  background: #031527;
}

.cpi-header-title {
  margin-bottom: 20px;
  display: flex;
  gap: 6px;
}

.cpi-header-text {
  margin-left: 6px;
}

.engine-config-title {
  margin: 0px 10px 0px 10px;
  display: flex;
  gap: 10px;
}

.engine-config-radio {
  margin: 20px 0 20px 12px;
}

.engine-config-radio-detail {
  margin: 20px 14px;
}

.engine-config-table {
  margin: 20px 0px 20px 12px;
}

.engine-config-is {
  display: flex;
  align-items: center;
  column-gap: 8px;
  margin-bottom: 20px;
}

.radio-group-row {
  display: flex;
  align-items: flex-start;
  gap: 40px;
}

.radio-wrapper {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.attached-select {
  margin-top: 6px;
  width: 200px;
}

.event {
  display: inline-block;
  margin-left: 10px;
}
</style>
